const db = require('../db');

const UserModel = {
    // 创建用户
    async createUser({
                         username,
                         phone,
                         password,
                         role = 2, // 默认普通用户
                         id_number = null,
                         bank_account = null,
                         bank_number = null,
                         avatar = null,
                         laborTeam = null,
                         status = 1
                     }) {
        const sql = `
            INSERT INTO users
            (username, phone, password, role, id_number, bank_account, bank_number, avatar, laborTeam, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `;
        const [result] = await db.execute(sql, [
            username,
            phone,
            password,
            role,
            id_number,
            bank_account,
            bank_number,
            avatar,
            laborTeam,
            status
        ]);
        return result.insertId;
    },

    // 获取所有有效用户（过滤掉已删除的）
    async getAllUsers() {
        const sql = `
            SELECT id, username, phone, role, id_number, bank_account, bank_number, recent_login, avatar, laborTeam, status, created_at, updated_at
            FROM users
            WHERE status != 2
        `;
        const [rows] = await db.execute(sql);
        return rows;
    },

    // 根据 ID 获取用户
    async getUserById(id) {
        const sql = `
            SELECT id, username, phone, role, id_number, bank_account, bank_number, recent_login, avatar, laborTeam, status, created_at, updated_at
            FROM users WHERE id = ?
        `;
        const [rows] = await db.execute(sql, [id]);
        return rows[0] || null;
    },

    // 根据用户名获取用户（含密码）
    async getUserByUsername(username) {
        const sql = `SELECT * FROM users WHERE username = ? AND status = 1 `;
        const [rows] = await db.execute(sql, [username]);
        return rows[0] || null;
    },

    // 根据手机号获取用户
    async getUserByPhone(phone) {
        const sql = `SELECT * FROM users WHERE phone = ? AND status = 1`;
        const [rows] = await db.execute(sql, [phone]);
        return rows[0] || null;
    },

    // 更新用户（支持多字段）
    async updateUser(id, updates) {
        const fields = [];
        const values = [];

        for (const key in updates) {
            if (updates[key] !== undefined) {
                fields.push(`${key} = ?`);
                values.push(updates[key]);
            }
        }

        if (fields.length === 0) return false;

        const sql = `
            UPDATE users SET ${fields.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?
        `;
        values.push(id);

        const [result] = await db.execute(sql, values);
        return result.affectedRows > 0;
    },

    // 软删除用户（将 status 设为 2）
    async deleteUser(id) {
        const sql = `UPDATE users SET status = 2, updated_at = CURRENT_TIMESTAMP WHERE id = ?`;
        const [result] = await db.execute(sql, [id]);
        return result.affectedRows > 0;
    },

    // 更新最近登录时间
    async updateRecentLogin(id) {
        const sql = `UPDATE users SET recent_login = NOW() WHERE id = ?`;
        await db.execute(sql, [id]);
    }
};

module.exports = UserModel;
